﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClassLibrary1;

namespace mana.lib.rates.service
{
    public class Rates
    {
        static IDictionary<DateTime, Decimal> _rates = new Dictionary<DateTime, Decimal>();
         

        public Decimal AddRate(DateTime dt, Decimal rt)
        {
            if (_rates.ContainsKey(dt))
            {
                throw new DuplicateRates();
            }
            DateTime x = new DateTime(DateTime.Now.Year, dt.Month, dt.Day);
            _rates.Add(dt, rt);
            return _rates[dt];
        }

        public Decimal GetRateForDate(DateTime dt)
        {
            Decimal? nextCycleRate = null;
            foreach (KeyValuePair<DateTime, Decimal> rate in _rates.OrderBy(rate => rate.Key))
            {
                if (nextCycleRate == null)
                    nextCycleRate = rate.Value;
                if (dt.Month < rate.Key.Month || (dt.Month == rate.Key.Month && dt.Day <= rate.Key.Day ) )
                    return rate.Value;
            }
            if (nextCycleRate != null)
                return (Decimal)nextCycleRate;

            throw new RateNotFoundException();
        }
    }
}
